<?php defined('SYSPATH') or die('No direct script access.');
/**
 * 商品管理
 *
 * @author  Yellow.Chow <aultoale@gmail.com>
 * @version $Id: item.php 1 2014-01-13 15:05:51Z zhouyl $
 * @license http://www.gnu.org/licenses/gpl-3.0.html    GPL 3
 */
class Controller_Admin_Store_Item extends Controller_Admin_Base
{
    public function action_index()
    {
        $this->view->keyword = trim($this->request->query('keyword'));

        $autosort = $this->autosort('item_id', 'desc');

        $sql = Model::factory('store_item')->all_sql()
            ->order_by($autosort->field, $autosort->direct);

        if ($this->view->keyword)
        {
            $sql->where('title', 'LIKE', '%'.$this->view->keyword.'%');
        }

        $this->view->pagination = new Pager($sql);
    }

    /**
     * 添加新商品
     */
    public function action_add()
    {
        $model = Model::factory('store_item');

        if ($this->request->is_post())
        {
            if ( ! $model->add($this->request->post()))
            {
                $this->view->errors = $model->errors('admin.store.item');
            }
            $this->render('admin/common/message');
        }

        $this->view->set('config', Config::get('items'));
    }

    /**
     * 编辑商品
     */
    public function action_edit()
    {
        $item_id = $this->request->param('id');
        $model = Model::factory('store_item');
        $item = $model->get($item_id);

        if ( ! $item)
        {
            $this->message('admin.store_item.not_found')
                ->link(URL::site('admin/store_item'), 'admin.store_item.index_url')
                ->render();
        }

        if ($this->request->is_post())
        {
            if ( ! $model->edit($item_id, $this->request->post()))
            {
                $this->view->errors = $model->errors('admin.store.item');
            }
            $this->render('admin/common/message');
        }

        $this->view->set($item);
        $this->view->set('config', Config::get('items'));
    }

    /**
     * 删除商品
     */
    public function action_del()
    {
        $item_id = $this->request->param('id');
        $model = Model::factory('store_item');

        if ( ! $model->del($item_id))
        {
            $this->view->errors = $model->errors('admin.store.item');
        }

        $this->render('admin/common/message');
    }

}